package com.projectbox.utility.impl;

import java.io.File;
import java.util.Hashtable;

import com.projectbox.utility.ResourceIconUtility;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

public class ResourceIconUtilityImpl implements ResourceIconUtility {
	
	//private final String resourceFileName = "/home/ec2-user/projectbox/resourceIcons.xml";
	private final String resourceFileName = "C:/projectbox/resourceIcons.xml"; 
	private Hashtable<String, String> resources = null;
    
	public String getResourceType(String type) {
		loadResourceFromXmlFile();
		
		return resources.get(type);
	}
	
	private void loadResourceFromXmlFile() {
		if (resources != null) {
			return;
		}
		
		try {
            File file = new File(resourceFileName);
            if (!file.exists()) { 
                return;
            }

            DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
            DocumentBuilder db = dbf.newDocumentBuilder();
            Document doc = db.parse(file);
            doc.getDocumentElement().normalize();
            NodeList nodeLst = doc.getElementsByTagName("resource");

            resources = new Hashtable<String, String>();
    		
            String type;
            String path;
            for (int s = 0; s < nodeLst.getLength(); s++) { 

                Node fstNode = nodeLst.item(s);

                if (fstNode.getNodeType() == Node.ELEMENT_NODE) {
                    // first Node
                    Element fstElmnt = (Element) fstNode;

                    // type
                    NodeList nameNmElmntLst = fstElmnt.getElementsByTagName("type");
                    Element nameNmElmnt = (Element) nameNmElmntLst.item(0);
                    NodeList nameNm = nameNmElmnt.getChildNodes();
                    type = (String) (((Node) nameNm.item(0)).getNodeValue());

                    // path
                    NodeList shareNmElmntLst = fstElmnt.getElementsByTagName("path");
                    Element shareNmElmnt = (Element) shareNmElmntLst.item(0);
                    NodeList shareNm = shareNmElmnt.getChildNodes();
                    path = (String) (((Node) shareNm.item(0)).getNodeValue());
                    
                    resources.put(type, path);
                }

            }
        } catch (Exception e) {
            e.printStackTrace();
        }
	}
}
